package com.cloudkinto.controller.orderoutput;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.service.orderoutput.OrderOutputService;
import com.cloudkinto.service.orderoutput.vo.*;
import com.cloudkinto.service.orderoutput.vo.cutoff.CutOffReq;
import com.cloudkinto.service.stock.StockRecordService;
import com.cloudkinto.service.orderoutput.vo.BatchPickUpReq;
import com.cloudkinto.service.stock.vo.record.StockRecordPageRes;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张永远
 * @since 2020-06-04
 */
@RestController
@Api(tags = "出库订单模块")
@RequestMapping("/api/admin/orderOutput")
public class OrderOutputController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(OrderOutputController.class);

    @Autowired
    private OrderOutputService service;
    @Autowired
    private StockRecordService stockRecordService;

    @UserSessionRequired
    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        return service.addInit(getCurrentUserId(), getCompanyId());
    }

    @UserSessionRequired
    @PostMapping("add")
    @ApiOperation(value = "新增", notes = "新增")
    public SingleResult add(@RequestBody @Validated OrderOutputAddReq req) {
        Long userId = getCurrentUserId();
        if (req.getCompanyId() == null || req.getCompanyId() == 0) {
            req.setCompanyId(getCompanyId());
        }
        return SingleResult.success("新增成功", service.add(req, userId));
    }

    @UserSessionRequired
    @PostMapping("reissue")
    @ApiOperation(value = "补发货", notes = "补发货")
    public SingleResult reissue(@RequestBody @Validated OrderOutputReissueReq req) {
        Long userId = getCurrentUserId();
        service.reissue(req, userId);
        return SingleResult.success();
    }


    @UserSessionRequired
    @GetMapping("/updateInit/{id}")
    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderOutputDetailRes.class)})
    public SingleResult<OrderOutputDetailRes> updateInit(@PathVariable("id") Long id) {
        return service.updateInit(id);
    }

    @UserSessionRequired
    @PutMapping("/update")
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult update(@RequestBody @Validated OrderOutputUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.update(req, userId));
    }

    @UserSessionRequired
    @PutMapping("/updateStock")
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult updateStock(@RequestBody @Validated OrderOutputUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.updateStock(req, userId));
    }

    @UserSessionRequired
    @PostMapping("/updateTrackNumber")
    @ApiOperation(value = "发货", notes = "发货")
    public SingleResult updateTrackNumber(@RequestBody @Validated OrderOutputUpdateTrackNumberReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success(service.updateTrackNumber(req, userId, getCompanyId()));
    }


    @UserSessionRequired
    @PostMapping("/batchSendApi")
    @ApiOperation(value = "发货", notes = "发货")
    public SingleResult batchSendApi(@RequestBody String[] ids) {
        Long userId = getCurrentUserId();
        service.batchSendApi(ids, userId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @GetMapping("/updateTrackNumberInit")
    @ApiOperation(value = "修改快递单号和快递公司初始化", notes = "修改快递单号和快递公司初始化")
    public SingleResult updateTrackNumberInit(Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success(service.updateTrackNumberInit(id, userId,getCompanyId()));
    }

    @UserSessionRequired
    @PutMapping("/order/cutoff")
    @ApiOperation(value = "截单", notes = "截单")
    public SingleResult cutoff(@RequestBody CutOffReq req) {
        Long userId = getCurrentUserId();
        service.cutoff(req, userId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @PutMapping("/order/finishCutOff/{id}")
    @ApiOperation(value = "完成截单", notes = "完成截单")
    public SingleResult finishCutOff(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        service.finishCutOff(id, userId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderOutputDetailRes.class)})
    public SingleResult<OrderOutputDetailRes> detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id));
    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit(getCompanyId(), getCurrentUserId());
    }

    @UserSessionRequired
    @GetMapping("/list")
    @ApiOperation(value = "查询", notes = "查询")
    @ApiImplicitParams(@ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"))
    public SingleResult list(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        map.put("keyword", keyword);
        return SingleResult.success("查询成功", service.getList(map));
    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "关键字搜索"),
            @ApiImplicitParam(name = "keyword", value = "关键字搜索"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页大小"),
            @ApiImplicitParam(name = "status", value = "订单状态"),
            @ApiImplicitParam(name = "multi", value = "包裹类型  1 一单一件 2一单多件"),
            @ApiImplicitParam(name = "trackId", value = "快递公司"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "shopId", value = "店铺id"),
            @ApiImplicitParam(name = "storageId", value = "仓库id")
            , @ApiImplicitParam(name = "startDate", value = "开始时间"),
            @ApiImplicitParam(name = "endDate", value = "结束时间")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderOutputListRes.class)})
    public PageResult<OrderOutputListRes> listPage(String keyword, String current, String pageSize, String multi, String checkType,
                                                   String status,   String dateType, String startDate, String endDate, String trackId, String shopId, String storageId) {
        Long shopIdcompanyId = getCompanyId();
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotBlank(keyword)) {
            StringBuilder result = new StringBuilder();
            keyword = keyword.trim();
            for (Character c : keyword.toCharArray()) {
                if (StringUtils.isNotBlank(c.toString()))
                    result.append("%").append(c);
            }
            map.put("keyword", result.toString());
        }
        map.put("current", current);
        map.put("pageSize", pageSize);
        map.put("status", status);
        map.put("multi", multi);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("trackId", trackId);
        map.put("storageId", storageId);
        map.put("checkType", checkType);
        map.put("dateType", dateType);
//        map.put("shopId", shopId);
//        map.put("orderType", "1");//一件代发
        if (shopId != null) {
            map.put("companyId", shopId + "");
        }
        return service.getListPage(map);
    }

    @UserSessionRequired
    @PostMapping("/uploadExcel")
    @ApiOperation(value = "导入发货单Excel", notes = "导入发货单Excel")
//    @ApiImplicitParams({@ApiImplicitParam(name = "file",value = "导入文件"  ,paramType = "file"), @ApiImplicitParam(name = "shopId", value = "店铺id"), @ApiImplicitParam(name = "storageId", value = "仓库id")})
    public SingleResult uploadExcel(MultipartFile file, Integer storageId, Integer shopId) {
        Long userid = getCurrentUserId();
        List<String> dataErrors = service.dealwithExcel(file, storageId, shopId, userid);
        return SingleResult.success(dataErrors);
    }

    @UserSessionRequired
    @GetMapping("/uploadExcelInit")
    @ApiOperation(value = "导入发货单Init", notes = "导入发货单ExcelInti")
//    @ApiImplicitParams({@ApiImplicitParam(name = "file",value = "导入文件"  ,paramType = "file"), @ApiImplicitParam(name = "shopId", value = "店铺id"), @ApiImplicitParam(name = "storageId", value = "仓库id")})
    public SingleResult uploadExcelInit() {
        Long userid = getCurrentUserId();
        List<Map> dataErrors = service.uploadExcelInit(userid);
        return SingleResult.success(dataErrors);
    }

    @UserSessionRequired
    @PostMapping("/uploadTrackNumberExcel")
    @ApiOperation(value = "导入快递单Excel", notes = "导入快递单Excel")
//    @ApiImplicitParams({@ApiImplicitParam(name = "file",value = "导入文件"  ,paramType = "file"), @ApiImplicitParam(name = "shopId", value = "店铺id"), @ApiImplicitParam(name = "storageId", value = "仓库id")})
    public SingleResult uploadTrackNumberExcel(MultipartFile file, Integer storageId) {
        Long userid = getCurrentUserId();
        Map data = service.dealwithTrackNumberExcel(file, storageId, userid);
        return SingleResult.success(SysConstant.OrderOutput_UploadExcel, data, data.get("count"));
    }


    @UserSessionRequired
    @PostMapping("/confirmSentOut")
    @ApiOperation(value = "导入快递单后 确认发货", notes = "导入快递单Excel")
    public SingleResult confirmSentOut(@RequestBody @Validated List<Long> orderListSuccess) {
        Long userid = getCurrentUserId();
        service.confirmSentOut(orderListSuccess, userid);
        return SingleResult.success(SysConstant.OrderOutput_Confirm_Success, "");
    }

    @UserSessionRequired
    @PostMapping("exportExcel")
    @ApiOperation(value = "导出所有数据excel")
    public void exportAll(@RequestBody OrderOutputExportReq req, HttpServletResponse response) throws Exception {

        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("companyId", req.shopId);
        map.put("storageId", req.storageId);
//        map.put("orderType", "1");//一件代发
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        else if (StringUtils.isNotBlank(req.getShopId())) {
            map.put("companyId", req.getShopId());
        }
        service.exportExcel(map, req.ids, response);
    }

    @UserSessionRequired
    @PostMapping("exportOtherStorageExpress")
    @ApiOperation(value = "导出导出特殊仓库快递面单")
    public void exportOtherStorageExpress(@RequestBody OrderOutputExportReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("companyId", req.shopId);
        map.put("storageId", req.storageId);
//        map.put("orderType", "1");//一件代发
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        service.exportOtherStorageExpress(map, req.ids, getCurrentUserId(), response);
    }

    @UserSessionRequired
    @PostMapping("exportOtherStorageEmailExpress")
    @ApiOperation(value = "导出合作仓库的文件并发送")
    public void exportOtherStorageEmailExpress(@RequestBody OrderOutputExportReq req) throws Exception {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("companyId", req.shopId);
        map.put("storageId", req.storageId);
//        map.put("orderType", "1");//一件代发
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        service.exportOtherStorageEmailExpress(map, req.ids, getCurrentUserId());
    }


    @UserSessionRequired
    @PostMapping("exportTrackExpress")
    @ApiOperation(value = "导出快递单")
    public void exportTrackExpress(@RequestBody OrderOutputExportReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("companyId", req.shopId);
        map.put("storageId", req.storageId);
//        map.put("orderType", "1");//一件代发
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        service.exportTrackExpress(map, req.ids, getCurrentUserId(), response);
    }

    @UserSessionRequired
    @PostMapping("exportTrackJPostExpress")
    @ApiOperation(value = "导出日本邮政特殊面单")
    public void exportTrackJPostExpress(@RequestBody OrderOutputExportReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("companyId", req.shopId);
        map.put("storageId", req.storageId);
//        map.put("orderType", "1");//一件代发
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        service.exportTrackJPostExpress(map, req.ids, getCurrentUserId(), response);
    }

    @UserSessionRequired
    @PostMapping("uploadTrackNumberData")
    @ApiOperation(value = "同步平台追踪号")
    public SingleResult uploadTrackNumberData(@RequestBody List<String> req) {
        service.uploadTrackNumberData(req, 0, getCurrentUserId());
        return SingleResult.success();
    }

    @UserSessionRequired
    @GetMapping("postExpress2Api")
    @ApiOperation(value = "postExpress2Api")
    public SingleResult postExpress2Api() {
        service.postExpress2Api();
        return SingleResult.success();
    }

    @UserSessionRequired
    @GetMapping("getExpress2Api")
    @ApiOperation(value = "getExpress2Api")
    public SingleResult getExpress2Api(String state) {
        service.getExpressStatus(state);
        return SingleResult.success();
    }

    @UserSessionRequired
    @PostMapping("shipfeeFix")
    @ApiOperation(value = "shipfeeFix")
    public SingleResult shipfeeFix(@RequestBody ShipFeeFixReq req) {
        service.shipfeeFix(req.getOrders(), req.getType(), getCurrentUserId());
        return SingleResult.success();
    }

    @UserSessionRequired
    @PostMapping("updateOrderWaitSend")
    @ApiOperation(value = "更改订单为待发货状态")
    public SingleResult updateOrderWaitSend(@RequestBody OrderOutputExportReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("comanyId", req.shopId);
        map.put("storageId", req.storageId);
//        map.put("orderType", "1");//一件代发
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }

        return service.updateOrderWaitSend(map, req.ids, getCurrentUserId(), response);
    }

//    @UserSessionRequired
//    @PostMapping("/batchUpdateOrderStatusCheckOut")
//    @ApiOperation(value = "PDA更新订单状态-已复核", notes = "")
//    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "关键字搜索")})
//    @ApiResponses({@ApiResponse(code = 200, message = "", response = OrderOutPickupInfoRes.class)})
//    public SingleResult batchUpdateOrderStatusCheckOut(@RequestBody List<ConsumablesCheckReq> reqs) {
//        return SingleResult.success(service.batchUpdateOrderStatusCheckOut(reqs, getCurrentUserId()));
//    }

    @UserSessionRequired
    @PostMapping("exportSkuTotal")
    @ApiOperation(value = "导出所有SKU小计")
    public void exportSkuTotal(@RequestBody OrderOutputExportReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("comanyId", req.shopId);
        map.put("storageId", req.storageId);
//        map.put("orderType", "1");//一件代发
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        service.exportSkuTotal(map, req.ids, getCurrentUserId(), response);
    }

    @UserSessionRequired
    @PostMapping("exportPickExcel")
    @ApiOperation(value = "导出拣货单")
    public void exportPickExcel(@RequestBody OrderOutputExportReq req, HttpServletResponse response) throws Exception {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("comanyId", req.shopId);
        map.put("storageId", req.storageId);
//        map.put("orderType", "1");//一件代发
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        service.exportPickExcel(map, req.ids, response);
    }


    @UserSessionRequired
    @GetMapping("/stockRecordListPage")
    @ApiOperation(value = "仓库商品查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "关键字搜索"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "pageSize", value = "页大小"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "shopId", value = "店铺id")})
    @ApiResponses({@ApiResponse(code = 200, message = "", response = StockRecordPageRes.class)})
    public PageResult<StockRecordPageRes> stockRecordListPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String shopId = request.getParameter("shopId");
        String storageId = request.getParameter("storageId");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        String productType = request.getParameter("productType");

        map.put("keyword", keyword);
        map.put("productType", productType);
        map.put("storageId", storageId);
        map.put("shopId", shopId);
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        map.put("current", current);
        map.put("pageSize", size);
        return stockRecordService.getListPage(map);
    }

    @UserSessionRequired
    @PostMapping("batchPickUp")
    @ApiOperation(value = "批量拣货", notes = "批量拣货")
    @ApiResponses({@ApiResponse(code = 200, message = "", response = BatchPickUpRes.class)})
    public SingleResult batchPickUp(@RequestBody BatchPickUpReq req) {
        return SingleResult.success(service.batchPickUp(req, getCurrentUserId(), getCompanyId()));
    }

    @UserSessionRequired
    @PostMapping("batchPickUpConfirm")
    @ApiOperation(value = "批量拣货预览确定按钮", notes = "批量拣货预览确定按钮")
    public SingleResult batchPickUpConfirm(@RequestBody BatchPickUpConfirmReq req) {
        return service.batchPickUpConfirm(req, getCurrentUserId(), getCompanyId());
    }


    @UserSessionRequired
    @PostMapping("exportYamatoSizeExcel")
    @ApiOperation(value = "导出yamato尺寸excel")
    public void exportYamatoSizeExcel(@RequestBody OrderOutputExportReq req, HttpServletResponse response) throws Exception {

        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        map.put("keyword", req.keyword);
        map.put("current", req.current);
        map.put("pageSize", req.pageSize);
        map.put("status", req.status);
        map.put("multi", req.multi);
        map.put("startDate", req.startDate);
        map.put("endDate", req.endDate);
        map.put("trackId", req.trackId);
        map.put("companyId", req.shopId);
        map.put("storageId", req.storageId);
//        map.put("orderType", "1");//一件代发
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        service.exportYamatoSizeExcel(map, req.ids, response);
    }

}

